import re

def parse_pattern(pattern):
    match = re.match(r'^(H\d+L\d+)\((\d+)\)$', pattern)
    if not match:
        raise ValueError("Invalid pattern format. Expected format: <pattern>(<number>)")
    inner_pattern = match.group(1)
    cycles = int(match.group(2))
    return inner_pattern, cycles

def expand_pattern(inner_pattern, cycles):
    signal = []
    high_low_matches = re.findall(r'H(\d+)|L(\d+)', inner_pattern)
    for _ in range(cycles):
        for match in high_low_matches:
            if match[0]:
                signal.extend([1] * int(match[0]))
            if match[1]:
                signal.extend([0] * int(match[1]))
    return signal

def generate_signal(pattern):
    def recursive_parse(pattern):
        nested_match = re.search(r'(H\d+L\d+\(\d+\))', pattern)
        if nested_match:
            before = pattern[:nested_match.start()]
            nested = nested_match.group(0)
            after = pattern[nested_match.end():]
            
            return recursive_parse(before) + recursive_parse(nested) + recursive_parse(after)
        else:
            if pattern:
                inner_pattern, cycles = parse_pattern(pattern)
                return expand_pattern(inner_pattern, cycles)
            else:
                return []
    
    return recursive_parse(pattern)

def save_to_raw_file(signal, filename):
    byte_array = bytearray(signal)
    with open(filename, 'wb') as f:
        f.write(byte_array)

# 示例模式
pattern = "H10L5(H2L1(2))H5L2(3)"
signal = generate_signal(pattern)

# 保存信号为二进制raw文件
save_to_raw_file(signal, 'signal.raw')

print("信号已保存为 'signal.raw'")